﻿#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QIcon>
#include "./module/can/CanTester.h"
#include "common/buttonmanager.h"
#include "common/backendprocessor.h"
#include "backend.h"
#include "module/uart/serialporthelper.h"
#include "module/uart/serialport.h"
#include "module/net/ethernet.h"
#include "module/pcie/PcieTest.h"
#include "module/gpio/GpioTest.h"
#include "module/i2c/I2CTest.h"
#include "module/spi/SpiTest.h"


int main(int argc, char *argv[])
{
    #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
        QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    #endif
        QGuiApplication app(argc, argv);

    // 设置不同平台的图标
    #ifdef Q_OS_WIN
        app.setWindowIcon(QIcon(":/icon/resource/favicon.ico")); // Windows平台使用 .ico 图标
    #elif defined(Q_OS_LINUX)
        app.setWindowIcon(QIcon(":/icon/resource/logo.png"));  // Linux平台使用 .png 图标
    #endif

    QQmlApplicationEngine engine;

    CanTester canTester;
    // 在程序启动的时候，起来了监控定时器
    BackendProcessor backendProcessor;
    // 创建Backend实例并注册到QML
    Backend backEnd;
    SerialPortHelper serialPortHelper;
    Ethernet etherNet;
    PcieTest pcieTest;
    GpioTest gpioTest;
    I2CTest i2CTest;
    SpiTest spiTest;

    // 注册 C++ 类到 QML
    engine.rootContext()->setContextProperty("cantester", &canTester);
    engine.rootContext()->setContextProperty("ethernet", &etherNet);
    engine.rootContext()->setContextProperty("pcietest", &pcieTest);
    engine.rootContext()->setContextProperty("gpiotest", &gpioTest);
    engine.rootContext()->setContextProperty("i2ctest", &i2CTest);
    engine.rootContext()->setContextProperty("spitest", &spiTest);
    engine.rootContext()->setContextProperty("backend", &backEnd);
    qmlRegisterType<SerialPort>("com.example.SerialPort", 1, 0, "SerialPort");
    //qmlRegisterSingletonInstance("com.example.backend", 1, 0, "Backend", &backend);
    qmlRegisterSingletonInstance("com.example.serialPortHelper", 1, 0, "SerialPortHelper", &serialPortHelper);
    qmlRegisterSingletonType<ButtonManager>("com.example.buttonmanager", 1, 0, "ButtonManager", [](QQmlEngine *, QJSEngine *) -> QObject * {
        qDebug() << "ButtonManager registered successfully.";
        return ButtonManager::instance();
    });
    //qmlRegisterType<Ethernet>("com.yourcompany.ethernettest", 1, 0, "Ethernet");

    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(
        &engine,
        &QQmlApplicationEngine::objectCreated,
        &app,
        [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        },
        Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}
